package com.daylive.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.daylive.model.Agent;
import com.daylive.model.Channel;
import com.daylive.model.SysMsg;
import com.daylive.model.TypeUser;
import com.daylive.model.User;
import com.daylive.page.Page;
import com.daylive.service.UserService;
import com.daylive.service.ChannelService;
import com.daylive.service.AgentService;
import com.daylive.util.ChatRoomUtil;
import com.daylive.util.DesTool;
import com.daylive.util.SdkHttpResult;
import com.daylive.util.StringUtil;


@Controller
@RequestMapping("user")
public class UserController {
	private final Logger logger = Logger.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private AgentService  agentService;
	@Autowired
	private ChannelService	ChannelService;
	private List<TypeUser>  typeUserList = null;
	private List<Channel>  getChannelPushList = null;
	private List<Agent>  agentList = null;
	public static HttpSession getSession() {
		HttpSession session = null;
		try {
			session = getRequest().getSession();
		} catch (Exception e) {
		}
		return session;
	}

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		return attrs.getRequest();
	}
	private void clearSession() {
		getSession().invalidate();
	}

	@RequestMapping("/user_list.do")
	public ModelAndView getUserList() {
		return getUserList(null,1);
	}
	@RequestMapping("/user_page_list.do")
	public ModelAndView getUserList(@RequestParam("name") String name,@RequestParam int pageNumber) {
		Page<User> pageList = userService.getUserList(name, pageNumber);
		ModelAndView mv = new ModelAndView("user_list");
		mv.addObject("currentPage", pageNumber);
		mv.addObject("name", name);
		mv.addObject("totalPage", pageList.getTotalPage());
		mv.addObject("totalCount", pageList.getTotalCount());
		mv.addObject("userList", pageList.getResultList());
		return mv;
	}
	 @RequestMapping("/user_add.do")
		public ModelAndView addUser() {
			ModelAndView mv = new ModelAndView();
			/*if(typeUserList == null || typeUserList.size() == 0) {
				this.typeUserList = userService.getTypeUserList();
			}*/
			if(agentList == null || agentList.size() == 0) {
				this.agentList = agentService.getAgentList();
			}
			this.getChannelPushList = ChannelService.getChannelPushList();
			mv.addObject("getChannelPushList", getChannelPushList);
			/*mv.addObject("typeUserList", typeUserList);*/
			mv.addObject("agentList", agentList);
			mv.setViewName("user_add");
			return mv;
		}
	   @RequestMapping("/user_save.do")
	   	public ModelAndView saveUser(User user) {
	   		ModelAndView mv = new ModelAndView();
	   		if(user.getPassword()==null||user.getPassword().equals("")){
	   			user.setPassword(DesTool.encode("111111"));
	   		}else {
				user.setPassword(DesTool.encode(user.getPassword()));
			}
		   	if (user.getType()==2) {
		   		user.setStartTime("");
		   		user.setEndTime("");
		   		if(user.getAmount()==null||user.getAmount().equals("")){
		   			user.setAmount("0");
		   		}
		   		if(user.getSingleConsumptionAmount()==null||user.getSingleConsumptionAmount().equals("")){
		   			user.setSingleConsumptionAmount("0");
		   		}
			}else{
				user.setAmount("0");
				user.setSingleConsumptionAmount("0");
			}
	   		Channel channel = ChannelService.getChannelById(user.getChannel_id());
	   		user.setChannel_push_url(channel.getChannel_push_url());
	   		user.setTime (StringUtil.getStrDate());
	   		int rel = userService.addUser(user);
	   		if(rel>0){
	   			try {
					SdkHttpResult token=ChatRoomUtil.getToken(String.valueOf(user.getId()), user.getName(), null);
					JSONObject myJsonObject = JSONObject.fromObject(token.getResult());
					String userToken = myJsonObject.getString("token");
					user.setName(user.getName());
					user.setToken(userToken);
					userService.updateUser(user);
				} catch (Exception e) {
					 userService.delUser(user.getId());
					mv.setViewName("error");
					mv.addObject("msg", "添加失败，请重新添加");
					e.printStackTrace();
					return mv; 
				}
	   		SysMsg msg =new SysMsg();
			msg.setTitle("亲爱的："+user.getName());
			msg.setContent("您好！恭喜您成为东方直播的用户!");
			msg.setReceiver_id(user.getId());
			msg.setTime(StringUtil.getStrDateTime());
			userService.addSysMsg(msg);
			mv.setViewName("success");
			mv.addObject("msg",rel > 0 ? "添加用户帐号成功！" : "数据添加失败！");
	   		}
	   		
			return mv;   		
	   	}
	  @RequestMapping("/user_edit.do")
		public ModelAndView editUser(@RequestParam("id")int id) {
	    	User users = userService.getUserById(id);
			ModelAndView mv = new ModelAndView();
			if(typeUserList == null || typeUserList.size() == 0) {
				this.typeUserList = userService.getTypeUserList();
			}
			if(agentList == null || agentList.size() == 0) {
				this.agentList = agentService.getAgentList();
			}
			this.getChannelPushList = ChannelService.getChannelPushList();
			mv.addObject("getChannelPushList", getChannelPushList);
			mv.addObject("typeUserList", typeUserList);
			mv.addObject("agentList", agentList);
			mv.addObject("user", users);
			mv.setViewName("user_edit");
			return mv;
		}
	    @RequestMapping("/user_update.do")
	   	public ModelAndView updateUser(User user) {
	   		ModelAndView mv = new ModelAndView();
	   		User user1 = userService.getUserById(user.getId());
	   		if (!user1.getPassword().equals(user.getPassword())) {
	   			user.setPassword(DesTool.encode(user.getPassword()));
			}
	   		Channel channel = ChannelService.getChannelById(user.getChannel_id());
	   		user.setChannel_push_url(channel.getChannel_push_url());
	   		int rel = userService.updateUser(user);
	   		mv.setViewName("success");
			mv.addObject("msg",rel > 0 ? "数据修改成功！" : "数据修改失败！");
			return mv;   		
	   	}
	    
	    @RequestMapping("/user_del.do")
		public String deleteUser(@RequestParam("id")int id) {
			 userService.delUser(id);
			return "success";
		}
	    
		@RequestMapping("/user_delAll.do")
		public String deleteAll(String ids) {
			String[] array_IDS = ids.split(",");
			userService.delAll(array_IDS);
			return "success";
		}
		/**
		 * check_user
		 * @return
		 */
		@RequestMapping("/user_check.do")
		@ResponseBody
	    public String checkUser(@RequestParam("account") String account) {  
			try {
				account = new String(account.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			User user = userService.getUserByAccount(account);
			return null==user ? "0" : "1";
		}
		/**
		 * check_phone
		 * @return
		 */
		@RequestMapping("/phone_check.do")
		@ResponseBody
	    public String checkPhone(@RequestParam("phone") String phone) {  
			User user = userService.getUserByPhone(phone);
			return null==user ? "0" : "1";
		}
		/**
		 * 修改时判断手机号是否存在
		 * check_phone
		 * @return
		 */
		@RequestMapping("/edit_phone_check.do")
		@ResponseBody
	    public String checkEditPhone(@RequestParam("phone") String phone,@RequestParam("id") int id) {  
			User  oldUser= userService.getUserById(id);
			User user = userService.getUserByPhone(phone);
			if (oldUser.getPhone().equals(phone)) {
				return "0";
			}else{
				return null==user ? "0" : "1";
			}
		}
		/**?
		 *邀请函设置页面
		 * @return
		 */
		@RequestMapping("/setting.do")
		public ModelAndView setting(@RequestParam("id") int id) {
			User user = userService.getUserById(id);
			ModelAndView mv = new ModelAndView("setting");
			mv.addObject("mailFormat", user.getMailFormat());
			mv.addObject("id", user.getId());
			return mv;
		}
		/**
		 * 邀请函设置
		 * @param mailFormat
		 * @return
		 */
		@RequestMapping("/mailFormat.do")
		public ModelAndView mailFormat(User user) {
			ModelAndView mv = new ModelAndView();
			int rel= userService.updateMailFormat(user);
			mv.setViewName("success");
			mv.addObject("msg",rel > 0 ? "数据修改成功！" : "数据修改失败！");
			return mv;
			}
}